package com.txt.result;

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.springframework.http.HttpStatus;

import java.io.Serializable;


@Getter
@Schema(description = "接口响应数据体")
@AllArgsConstructor
public class R<T> implements Serializable
{
    private static final long serialVersionUID = 1L;

    /** 成功 */
    public static final int SUCCESS = HttpStatus.OK.value();

    /** 失败 */
    public static final int FAIL = HttpStatus.INTERNAL_SERVER_ERROR.value();

    /** 警告 */
    public static final int WARN = 601;

    @Schema(description = "响应状态码", example = "200")
    private int code;

    @Schema(description = "响应信息")
    private String msg;

    @Schema(description = "响应数据")
    private T data;

    public static <T> R<T> ok()
    {
        return restResult(null, SUCCESS, "操作成功");
    }

    public static <T> R<T> ok(T data)
    {
        return restResult(data, SUCCESS, "操作成功");
    }

    public static <T> R<T> ok(T data, String msg)
    {
        return restResult(data, SUCCESS, msg);
    }

    public static <T> R<T> fail()
    {
        return restResult(null, FAIL, "操作失败");
    }

    public static <T> R<T> fail(String msg)
    {
        return restResult(null, FAIL, msg);
    }

    public static <T> R<T> fail(T data)
    {
        return restResult(data, FAIL, "操作失败");
    }

    public static <T> R<T> fail(T data, String msg)
    {
        return restResult(data, FAIL, msg);
    }

    public static <T> R<T> fail(int code, String msg)
    {
        return restResult(null, code, msg);
    }

    public static <T> R<T> warn(String msg)
    {
        return restResult(WARN, msg);
    }

    private static <T> R<T> restResult( int code, String msg)
    {
        return new R<>(code, msg, null);
    }

    private static <T> R<T> restResult(T data, int code, String msg)
    {
        return new R<>(code, msg, data);
    }
}
